﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;

namespace SuperDeepZoom.ImageData
{
    internal class SubImageMetadataManager
    {

        WebClient webClientDownloader = new WebClient();
        
        string imageDataXml;

        Uri imageData;

        List<SubImageMetadata> subImageMetadataList = null;

        public event EventHandler DataLoaded;

        public SubImageMetadataManager(string path)
        {
            if (path.Contains(".xml"))
            {
                path = path.Substring(0, path.LastIndexOf("/"));
            }

            //If the url starts with . (as in ../) or / (as in /somthing.xml) then it is relative, otherwise let it load from anywhere             
            if (path.StartsWith("."))
            {

                imageData = new Uri(Application.Current.Host.Source, new Uri(path + "/ImageData.xml", UriKind.Relative));
            }
            else
            {
                imageData = new Uri(path + "/ImageData.xml", UriKind.RelativeOrAbsolute);
            }

            webClientDownloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientDownloader_DownloadStringCompleted);
            downloadImageData();
        }

        void downloadImageData()
        {
            webClientDownloader.DownloadStringAsync(imageData);
        }

        protected void OnManifestLoaded()
        {
            if (!string.IsNullOrEmpty(imageDataXml))
            {

                //Load up the image data from the XML file. This data is used for
                //information display and filtering.
                List<SubImageMetadata> result = new List<SubImageMetadata>();
                XDocument imageDataDoc = XDocument.Parse(imageDataXml);
                imageDataDoc.Root.Elements("Image").ToList<XElement>().ForEach(
                        p =>
                        {
                            //note the id must be one less than the zorder from 
                            //the metadata file... 
                            int id = Convert.ToInt32(p.Attribute("id").Value);
                            string url = p.Attribute("url").Value;
                            string tag = p.Attribute("tag").Value;
                            string title = p.Attribute("title").Value;
                            string blurb = p.Value.Trim();

                            //map this id back to the original collection
                            SubImageMetadata item = new SubImageMetadata(id, tag)
                            {
                                Blurb = blurb,
                                Title = title,
                                Url = url
                            };
                            result.Add(item);

                        }
                    );                

                subImageMetadataList = result;

                if (DataLoaded != null)
                {
                    DataLoaded(this, EventArgs.Empty);

                }
            }
        }

        /// <summary>
        /// Once the manifest is downloaded, call the OnManifestLoaded method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void webClientDownloader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                imageDataXml = e.Result;
                OnManifestLoaded();
            }
            else
            {
                throw e.Error;
            }
        }

        public List<SubImageMetadata> SubImageMetadataList
        {
            get
            {
                return subImageMetadataList;
            }
        }

    }
}
